package logic

import (
	"context"
	"course_srv/models/mysql"

	"course_srv/course"
	"course_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CourseListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCourseListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CourseListLogic {
	return &CourseListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CourseListLogic) CourseList(in *course.CourseListRequest) (*course.CourseListResponse, error) {
	// todo: add your logic here and delete this line

	var c []mysql.Course
	query := mysql.DB.Scopes(mysql.Paginate(int(in.Page), int(in.PageSize))) //计算分页
	if in.Name != "" {
		query = query.Where("name like ?", "%"+in.Name+"%") //模糊搜索
	}
	query.Order("price desc").Find(&c) //排序
	var slice []*course.CourseList
	for _, v := range c {
		slice = append(slice, &course.CourseList{
			Id:     int32(v.ID),
			Name:   v.Name,
			Stock:  int32(v.Stock),
			Price:  float32(v.Price),
			Cover:  v.Cover,
			Intro:  v.Intro,
			Status: int32(v.Status),
		})
	}
	return &course.CourseListResponse{List: slice}, nil
}
